//
//  SNProductionPlanningViewController.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/23.
//  Copyright © 2016年 stone. All rights reserved.
//


#import "NSDate+TimeStamp.h"
#import "MJRefresh.h"
#import "SNPlantingDecisionMakerModel.h"
#import "SNProductionEmptyPlanningCell.h"
#import "SNPlanListViewController.h"
#import "SNProductionSiftView.h"
#import "SNProductionSearchView.h"
#import "SNProductionPlanningCell.h"
#import "SNProductionPlanningViewController.h"
#import "Masonry.h"
#import "SNOrganizationModel.h"
static BOOL __needUPDate = NO;
static NSString * __fullName = nil;
@interface SNProductionPlanningViewController ()<UITableViewDataSource,UITableViewDelegate>
/** firstLoad */
@property (nonatomic, assign,getter=isFirstLoad) BOOL firstLoad;
/**
 *  当前页数
 */
@property (nonatomic, assign) NSInteger currentPage;
/**
 *  总页数
 */
@property (nonatomic, assign) NSInteger totalPage;

/** SNPlantingDecisionMakerModel * plantingDecisionMakerModel */
@property (nonatomic,strong) SNPlantingDecisionMakerModel * plantingDecisionMakerModel;
/** searchView */
@property (weak, nonatomic) SNProductionSearchView * searchView;
/** tableView */
@property (nonatomic,weak) UITableView * tableView;

/** selectedIndexs */
@property (nonatomic,strong) NSMutableArray<NSNumber *> * selectedIndexs;
@property (nonatomic, strong) NSMutableArray<SNOrganizationResult *> *organizationModels;
@end

@implementation SNProductionPlanningViewController

+ (BOOL)getNeedUPDate{
    return __needUPDate;
}
+ (void)setNeedUPDate:(BOOL)needUPDate{
    __needUPDate = needUPDate;
}
+ (NSString *)getFullName{
    return __fullName;
}
+ (void)setFullName:(NSString *)fullName{
    __fullName = fullName;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.isFirstLoad) {
        self.firstLoad = NO;
    }else{
        
        [[ZXHTTPManager sharedManager] viewruleplanWithUserId:kUserInfo.userId year:[self getYear] currentPage:@"1" pageSize:@"15" custName:__fullName completed:^(NSDictionary *jsonDict, NSError *error) {
            
            logError;
            
            NSLog(@"%@",jsonDict);
            
            SNPlantingDecisionMakerModel * plantingDecisionMakerModel = [SNPlantingDecisionMakerModel mj_objectWithKeyValues:jsonDict];
            if(plantingDecisionMakerModel.status.integerValue == 0){
                
                self.plantingDecisionMakerModel = plantingDecisionMakerModel;
                
                self.currentPage = plantingDecisionMakerModel.currentPage.integerValue;
                self.totalPage = plantingDecisionMakerModel.totalPage.integerValue;
                
                [self.tableView reloadData];
            }else{
                [SNUtils alertViewWithViewController:self message:plantingDecisionMakerModel.message confirmBlock:^{
                  
                    // 确定之后要做的事...
                }];
            }
        }];
        
        if (__needUPDate == YES) {
            //更新
            self.searchView.textField.text = __fullName;
        }
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.firstLoad = YES;
    self.navigationItem.title = @"种植决策人清单";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view, typically from a nib.
    [self addObserver];
    [self addViews];
    [self setupUI];
    
}
- (void)fooWithUserId:(NSString *)userId orgtype:(NSString *)orgtype fullName:(NSString *)fullName
{
    //    [[ZXHTTPManager sharedManager] viewOrgInfoWithUserId:userId orgtype:orgtype completed:^(NSDictionary *jsonDict, NSError *error) {
    //
    //        logError;
    //
    //        NSLog(@"%@",jsonDict);
    //
    //        SNOrganizationModel * organizationModel = [SNOrganizationModel mj_objectWithKeyValues:jsonDict];
    //        if(organizationModel.status.integerValue == 0){
    //            //成功
    //
    //            self.organizationModels = organizationModel.result.mutableCopy;
    //
    //            [self.tableView reloadData];
    //        }else{
    //
    //        }
    //    }];
}
- (NSMutableString *)filterData:(NSArray<SNProductionSiftButton *> *)buttons
{
    self.selectedIndexs = [NSMutableArray array];
    NSMutableString * strM = @"[".mutableCopy;
    
    for(int i = 0; i < buttons.count; i++) {
        SNProductionSiftButton * siftButton = buttons[i];
        
        if (siftButton.selected) {
            [strM appendFormat:@"'%d',",i+1];
            [self.selectedIndexs addObject:@(i)];
        }
    }
    
    NSRange range = [strM rangeOfString:@"," options:NSBackwardsSearch];
    
    if (range.location != NSNotFound) {
        [strM deleteCharactersInRange:range];
        [strM appendString:@"]"];
    }else{
        [strM appendString:@"'1','2','3']"];
    }
    return strM;
}
- (NSString *)getYear
{
    NSString * searchText = self.searchView.titleLabel.text;
    
    NSString * RegExString = @"\\d{4}";
    
    NSRange range = [searchText rangeOfString:RegExString options:NSRegularExpressionSearch];
    
    NSLog(@"%@",  [searchText substringWithRange:range]);
    
    return [searchText substringWithRange:range];
}
- (void)addViews
{
    SNProductionSearchView * searchView = ({
        SNProductionSearchView * view = [[SNProductionSearchView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 46)];
        
        view.backgroundColor = HexRGB(0xf5f5f5);//[UIColor orangeColor];//
        view.nav = self.navigationController;
        
//        @weakify_self
//        [view setSiftBlock:^{
//            @strongify_self
//            /** 蒙版 */
//            UIView * bgView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//            bgView.backgroundColor = [UIColor blackColor];
//            bgView.alpha = 0.0;
//            [self.navigationController.view addSubview:bgView];
//            //sn_note:=========  ============================ stone 🐳 ===========/
//            
//            SNProductionSiftView * siftView =  [SNProductionSiftView view];
//            siftView.bgView = bgView;
//            
//            if (self.selectedIndexs.count > 0) {
//                siftView.selectedIndexs = self.selectedIndexs;
//            }
//            
//            @weakify_self
//            [siftView setDownButtonClickedBlock:^(NSArray<SNProductionSiftButton *> * buttons) {
//                @strongify_self
//                //  @"['1','2','3']"
//                NSMutableString * strM = [self filterData:buttons];
//                
//                [self fooWithUserId:kUserInfo.userId orgtype:strM];
//            }];
//            
//            CGFloat w = 338 / 375.0 * [UIScreen mainScreen].bounds.size.width;
//            siftView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width, 0, w, [UIScreen mainScreen].bounds.size.height);
//            
//            [self.navigationController.view addSubview:siftView];
//            
//            [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
//                bgView.alpha = 0.7;
//                //
//                CGFloat w = 338 / 375.0 * [UIScreen mainScreen].bounds.size.width;
//                siftView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - w, 0, w, [UIScreen mainScreen].bounds.size.height);
//            } completion:^(BOOL finished) {
//                //
//            }];
//        }];
        
        [self.view addSubview:view];
        
        view;
    });
    
    self.searchView = searchView;
    //sn_note:========= add tableView ============================ stone 🐳 ===========/
    
    
    CGRect frame = CGRectMake(0, CGRectGetMaxY(searchView.frame)+10, self.view.bounds.size.width, self.view.bounds.size.height - CGRectGetMaxY(searchView.frame)-10);
    UITableView * tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
    self.tableView = tableView;
    tableView.backgroundColor = HexRGB(0xf5f5f5);//[UIColor lightGrayColor];//
    [self setupInit:tableView];
    
    [self.view addSubview:tableView];
    
    [self addRequest];
    
    [self.view bringSubviewToFront:searchView];
    
    [tableView reloadData];
}
- (void)setupUI
{
    
}
#pragma mark - <addRequest>
- (void)addRequest {
    // addRequest
    NSString * yearString = [NSDate new].dateToString(@"yyyy");
    
    NSLog(@"yearString = %@",yearString);
    
    [[ZXHTTPManager sharedManager] viewruleplanWithUserId:kUserInfo.userId year:yearString currentPage:@"1" pageSize:@"15" custName:nil completed:^(NSDictionary *jsonDict, NSError *error) {
        
        logError;
        
        NSLog(@"%@",jsonDict);
        
        SNPlantingDecisionMakerModel * plantingDecisionMakerModel = [SNPlantingDecisionMakerModel mj_objectWithKeyValues:jsonDict];
        
        self.plantingDecisionMakerModel = plantingDecisionMakerModel;
        
        self.currentPage = plantingDecisionMakerModel.currentPage.integerValue;
        self.totalPage = plantingDecisionMakerModel.totalPage.integerValue;
        
        [self.tableView reloadData];
    }];
    
    //    NSString * filePath = [[NSBundle mainBundle] pathForResource:@"jihua.json" ofType:nil];
    //    NSData * data = [NSData dataWithContentsOfFile:filePath];
    //
    //
    //    NSDictionary * jsonDict =    [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:NULL];
    //
    //    SNPlantingDecisionMakerModel * plantingDecisionMakerModel = [SNPlantingDecisionMakerModel mj_objectWithKeyValues:jsonDict];
    //
    //    self.plantingDecisionMakerModel = plantingDecisionMakerModel;
    //    //
    //    [self.tableView reloadData];
}
- (void)didReceivedUpdateYearNotification:(NSNotification *)notify
{
    [[ZXHTTPManager sharedManager] viewruleplanWithUserId:kUserInfo.userId year:[self getYear] currentPage:@"1" pageSize:@"15" custName:nil completed:^(NSDictionary *jsonDict, NSError *error) {
        
        logError;
        
        NSLog(@"%@",jsonDict);
        
        SNPlantingDecisionMakerModel * plantingDecisionMakerModel = [SNPlantingDecisionMakerModel mj_objectWithKeyValues:jsonDict];
        
        self.plantingDecisionMakerModel = plantingDecisionMakerModel;
        
        self.currentPage = plantingDecisionMakerModel.currentPage.integerValue;
        self.totalPage = plantingDecisionMakerModel.totalPage.integerValue;
        
        [self.tableView reloadData];
    }];
}
#pragma mark - <addObserver>
- (void)addObserver {
    // addObserver
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceivedUpdateYearNotification:) name:@"UpdateYearNotification" object:nil];
    
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"%@ %s %@",[self class], __func__ , @"im dying");
    __fullName = nil;
    __needUPDate = NO;
}

- (void)setupInit:(UITableView *)tableView {
    tableView.delegate = self;
    tableView.dataSource = self;
    
    UIView * footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 10)];
    footerView.backgroundColor = HexRGB(0xf5f5f5);
    tableView.tableFooterView = footerView;
    
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self setHeights:tableView];
    [self registerNib:tableView];
    [self registerClass:tableView];
    [self addHeaderFooterRefresh:tableView];
}
- (void)addHeaderFooterRefresh:(UITableView *)tableView {
    
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestNew)];
    /** view创建 就刷新 , 不想用... */
    //    [tableView.gb_header beginRefreshing];
    
    tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMore)];
}
- (void)requestNew {
    
    self.currentPage = 1;
    self.totalPage = 0;
    
    [[ZXHTTPManager sharedManager] viewruleplanWithUserId:kUserInfo.userId year:[self getYear] currentPage:@"1" pageSize:@"15" custName:nil completed:^(NSDictionary *jsonDict, NSError *error) {
        
        if (error) {
            NSLog(@"error = %@",error);
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
            return;
        }
        
        NSLog(@"%@",jsonDict);
        
        SNPlantingDecisionMakerModel * plantingDecisionMakerModel = [SNPlantingDecisionMakerModel mj_objectWithKeyValues:jsonDict];
        
        self.currentPage = plantingDecisionMakerModel.currentPage.integerValue;
        self.totalPage = plantingDecisionMakerModel.totalPage.integerValue;
        
        self.plantingDecisionMakerModel = plantingDecisionMakerModel;
        
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer resetNoMoreData];
    }];
    
    
}
- (void)requestMore {
    
    if (self.currentPage < self.totalPage) {
        self.currentPage++;
        // 网络请求
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //
        ////            self.tableView.sectionCount += 5;
        //            // 刷新表格
        //            [self.tableView reloadData];
        //
        //            // 拿到当前的下拉刷新控件，结束刷新状态
        //            [self.tableView.mj_footer endRefreshing];
        //        });
        
        [[ZXHTTPManager sharedManager] viewruleplanWithUserId:kUserInfo.userId year:[self getYear] currentPage:[NSString stringWithFormat:@"%ld",self.currentPage] pageSize:@"15" custName:nil completed:^(NSDictionary *jsonDict, NSError *error) {
            
            if (error) {
                NSLog(@"error = %@",error);
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer resetNoMoreData];
                return;
            }
            
            NSLog(@"%@",jsonDict);
            
            SNPlantingDecisionMakerModel * plantingDecisionMakerModel = [SNPlantingDecisionMakerModel mj_objectWithKeyValues:jsonDict];
            
            self.currentPage = plantingDecisionMakerModel.currentPage.integerValue;
            self.totalPage = plantingDecisionMakerModel.totalPage.integerValue;
            
            NSArray * array =  [self.plantingDecisionMakerModel.result arrayByAddingObjectsFromArray:plantingDecisionMakerModel.result];
            self.plantingDecisionMakerModel.result = array;
            [self.tableView reloadData];
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
        }];
        
    } else {
        
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //
    //      self.sectionCount += 5;
    //      // 刷新表格
    //      [self reloadData];
    //
    //      // 拿到当前的下拉刷新控件，结束刷新状态
    //      [self.gb_footer endRefreshing];
    //
    //      if (self.totalPage >= 50) {
    //          [self.gb_footer endRefreshingWithNoMoreData];
    //      } else {
    //          [self.gb_footer endRefreshing];
    //      }
    //    });
}
#pragma mark - <Register>
/** registerNib */
- (void)registerNib:(UITableView *)tableView {
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SNProductionPlanningCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([SNProductionPlanningCell class])];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SNProductionEmptyPlanningCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([SNProductionEmptyPlanningCell class])];
    
}
/** registerClass */
- (void)registerClass:(UITableView *)tableView {
    
    // [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    
    [tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([UITableViewHeaderFooterView class])];
}

#pragma mark - <SetHeights>
/** setHeights */
- (void)setHeights:(UITableView *)tableView {
    
    /** header */
    tableView.sectionHeaderHeight = 10;
    // tableView.estimatedSectionHeaderHeight = 100;
    // tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
    /** cell */
    tableView.estimatedRowHeight = 100;
    tableView.rowHeight = UITableViewAutomaticDimension;
    /** footer */
    tableView.sectionFooterHeight = 0.001;
    // tableView.estimatedSectionFooterHeight = 100;
    // tableView.sectionFooterHeight = UITableViewAutomaticDimension;
}

#pragma mark - <UITableViewDataSource>
/** 组数 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.plantingDecisionMakerModel.result.count;
}
/** 行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
#pragma mark - <UITableViewDelegate>

//MARK: -
//MARK: - cell
/** cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    SNPlantingDecisionMakerResult * model =  self.plantingDecisionMakerModel.result[indexPath.section];
    
    if(model.approval.length == 0 && model.passed.length == 0 && model.draft.length == 0 && model.repealed.length == 0){
        
        SNProductionEmptyPlanningCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SNProductionEmptyPlanningCell class])];
        cell.model = model;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else{
        
        SNProductionPlanningCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SNProductionPlanningCell class])];
        cell.model = model;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
    
    //    if (indexPath.section % 2 == 0) {
    //        SNProductionPlanningCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SNProductionPlanningCell class])];
    //
    //        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    //        return cell;
    //    }else{
    //        SNProductionEmptyPlanningCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SNProductionEmptyPlanningCell class])];
    //
    //        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    //        return cell;
    //    }
    
    
}
#pragma mark - <UITableViewDelegate>

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.001;
}

/** 选中一行 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __func__);
    //    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    SNPlantingDecisionMakerResult * plantingDecisionMakerResult =  self.plantingDecisionMakerModel.result[indexPath.section];
    
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([cell isKindOfClass:[SNProductionPlanningCell class]]) {
        SNPlanListViewController * vc = [SNPlanListViewController new];
        vc.empty = NO;
        vc.plantingDecisionMakerResult = plantingDecisionMakerResult;
        vc.year = self.searchView.titleLabel.text;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([cell isKindOfClass:[SNProductionEmptyPlanningCell class]]){
        SNPlanListViewController * vc = [SNPlanListViewController new];
        vc.empty = YES;
        vc.plantingDecisionMakerResult = plantingDecisionMakerResult;
        vc.year = self.searchView.titleLabel.text;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}
/** 取消 选中 */
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0) {
    NSLog(@"%s", __func__);
}

@end
